<template>
  <el-card v-loading="loading" class="question-card">
    <!-- 题型标签页 -->
    <el-tabs v-model="activeTab" class="question-tabs" type="border-card">
      <el-tab-pane label="单选题" name="single">
        <keep-alive>
          <div v-show="activeTab === 'single'" class="question-list">
            <div v-for="(_, index) in singleChoiceForms" :key="index" class="question-item">
              <single-choice
                :ref="(el) => (singleChoiceRefs[index] = el)"
                :question-index="index"
                @add-question="addQuestion"
                @remove-question="removeQuestion(index)"
              />
            </div>
          </div>
        </keep-alive>
      </el-tab-pane>

      <el-tab-pane label="多选题" name="multiple">
        <keep-alive>
          <div v-show="activeTab === 'multiple'" class="question-list">
            <div v-for="(_, index) in multipleChoiceForms" :key="index" class="question-item">
              <multiple-choice
                :ref="(el) => (multipleChoiceRefs[index] = el)"
                :question-index="index"
                @add-question="addMultipleQuestion"
                @remove-question="removeMultipleQuestion(index)"
              />
            </div>
          </div>
        </keep-alive>
      </el-tab-pane>

      <el-tab-pane label="判断题" name="judge">
        <keep-alive>
          <div v-show="activeTab === 'judge'" class="question-list">
            <div v-for="(_, index) in judgeForms" :key="index" class="question-item">
              <judge-choice
                :ref="(el) => (judgeChoiceRefs[index] = el)"
                :question-index="index"
                @add-question="addJudgeQuestion"
                @remove-question="removeJudgeQuestion(index)"
              />
            </div>
          </div>
        </keep-alive>
      </el-tab-pane>

      <el-tab-pane label="简答题" name="short">
        <keep-alive>
          <div v-show="activeTab === 'short'" class="question-list">
            <div v-for="(_, index) in shortAnswerForms" :key="index" class="question-item">
              <short-answer
                :ref="(el) => (shortAnswerRefs[index] = el)"
                :question-index="index"
                @add-question="addShortQuestion"
                @remove-question="removeShortQuestion(index)"
              />
            </div>
          </div>
        </keep-alive>
      </el-tab-pane>

      <el-tab-pane label="填空题" name="blank">
        <keep-alive>
          <div v-show="activeTab === 'blank'" class="question-list">
            <div v-for="(_, index) in blankForms" :key="index" class="question-item">
              <blank-fill
                :ref="(el) => (blankRefs[index] = el)"
                :question-index="index"
                @add-question="addBlankQuestion"
                @remove-question="removeBlankQuestion(index)"
              />
            </div>
          </div>
        </keep-alive>
      </el-tab-pane>
    </el-tabs>

    <!-- 新增题目按钮 -->
    <div v-if="shouldShowAddButton" class="empty-state">
      <el-button type="primary" @click="handleAddQuestion">
        <el-icon>
          <Plus />
        </el-icon>
        新增题目
      </el-button>
    </div>

    <!-- 操作按钮 -->
    <div v-if="!shouldShowAddButton" class="form-actions">
      <div class="fixed-bottom">
        <el-button type="primary" @click="submitForm">提交题目</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { useQuestionStore } from '@/store/modules/material/question'
import { Plus } from '@element-plus/icons-vue'
import SingleChoice from './components/SingleChoice.vue'
import MultipleChoice from './components/MultipleChoice.vue'
import JudgeChoice from './components/JudgeChoice.vue'
import ShortAnswer from './components/ShortAnswer.vue'
import BlankFill from './components/BlankFill.vue'
import * as QuestionApi from '@/api/material/question'
import { useTagsView } from '@/hooks/web/useTagsView'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const { closeCurrent } = useTagsView()
const questionStore = useQuestionStore()
const { singleChoiceForms, multipleChoiceForms, judgeForms, shortAnswerForms, blankForms } =
  storeToRefs(questionStore)
const {
  addSingleChoiceForm,
  removeSingleChoiceForm,
  addMultipleChoiceForm,
  removeMultipleChoiceForm,
  addJudgeForm,
  removeJudgeForm,
  addShortAnswerForm,
  removeShortAnswerForm,
  addBlankForm,
  removeBlankForm,
  updateSingleChoiceForm,
  updateMultipleChoiceForm,
  updateJudgeForm,
  updateShortAnswerForm,
  updateBlankForm
} = questionStore

// 当前激活的标签页
const activeTab = ref('single')

// 使用数组存储组件引用
const singleChoiceRefs = ref<any[]>([])
const multipleChoiceRefs = ref<any[]>([])
const judgeChoiceRefs = ref<any[]>([])
const shortAnswerRefs = ref<any[]>([])
const blankRefs = ref<any[]>([])

// 获取路由参数
const questionId = computed(() => route.query.id as string)
const editType = computed(() => route.query.type as string)

// 初始化编辑数据
const initEditData = async () => {
  if (!questionId.value) return

  loading.value = true
  try {
    const data = await QuestionApi.getQuestion(parseInt(questionId.value))
    if (!data) {
      ElMessage.error('获取题目详情失败')
      return
    }

    // 等待下一个tick，确保组件已经完全挂载
    await nextTick()

    // 根据题目类型切换到对应标签页并填充数据
    switch (data.type) {
      case 'single':
        activeTab.value = 'single'
        const singleIndex = addSingleChoiceForm()
        await nextTick() // 等待表单数据初始化

        // 解析 options 字符串为对象数组
        let parsedOptions = []
        try {
          parsedOptions = JSON.parse(data.options)
        } catch (e) {
          console.error('解析选项数据失败:', e)
          parsedOptions = []
        }

        updateSingleChoiceForm(singleIndex, 'id', data.id)
        updateSingleChoiceForm(singleIndex, 'title', data.content)
        updateSingleChoiceForm(singleIndex, 'options', parsedOptions)
        updateSingleChoiceForm(singleIndex, 'answer', data.answer)
        updateSingleChoiceForm(singleIndex, 'analysis', data.analysis || '')
        updateSingleChoiceForm(singleIndex, 'difficulty', data.difficulty)
        updateSingleChoiceForm(singleIndex, 'classId', data.classId)
        break
      case 'multiple':
        activeTab.value = 'multiple'
        const multipleIndex = addMultipleChoiceForm()
        await nextTick()

        // 解析多选题的 options
        let parsedMultipleOptions = []
        try {
          parsedMultipleOptions = JSON.parse(data.options)
        } catch (e) {
          console.error('解析多选题选项数据失败:', e)
          parsedMultipleOptions = []
        }

        updateMultipleChoiceForm(multipleIndex, 'id', data.id)
        updateMultipleChoiceForm(multipleIndex, 'title', data.content)
        updateMultipleChoiceForm(multipleIndex, 'options', parsedMultipleOptions)
        updateMultipleChoiceForm(multipleIndex, 'answer', data.answer ? data.answer.split(',') : [])
        updateMultipleChoiceForm(multipleIndex, 'analysis', data.analysis || '')
        updateMultipleChoiceForm(multipleIndex, 'difficulty', data.difficulty)
        updateMultipleChoiceForm(multipleIndex, 'classId', data.classId)
        break
      case 'judge':
        activeTab.value = 'judge'
        const judgeIndex = addJudgeForm()
        await nextTick()

        // 解析判断题的 options
        let parsedJudgeOptions = []
        try {
          parsedJudgeOptions = JSON.parse(data.options)
        } catch (e) {
          parsedJudgeOptions = [
            { key: 'A', value: '正确' },
            { key: 'B', value: '错误' }
          ]
        }

        updateJudgeForm(judgeIndex, 'id', data.id)
        updateJudgeForm(judgeIndex, 'title', data.content)
        updateJudgeForm(judgeIndex, 'options', parsedJudgeOptions)
        updateJudgeForm(judgeIndex, 'answer', data.answer)
        updateJudgeForm(judgeIndex, 'analysis', data.analysis || '')
        updateJudgeForm(judgeIndex, 'difficulty', data.difficulty)
        updateJudgeForm(judgeIndex, 'classId', data.classId)
        break
      case 'short':
        activeTab.value = 'short'
        const shortIndex = addShortAnswerForm()
        await nextTick() // 等待表单数据初始化

        // 将逗号分隔的关键字字符串转换为数组
        let keywordsArray = []
        if (data.keywords) {
          // 处理字符串格式的关键字
          if (typeof data.keywords === 'string') {
            keywordsArray = data.keywords.split(',').filter((k) => k.trim())
          }
          // 处理数组格式的关键字
          else if (Array.isArray(data.keywords)) {
            keywordsArray = data.keywords
          }
        }

        updateShortAnswerForm(shortIndex, 'id', data.id)
        updateShortAnswerForm(shortIndex, 'title', data.content)
        updateShortAnswerForm(shortIndex, 'answer', data.answer)
        updateShortAnswerForm(shortIndex, 'keywords', keywordsArray)
        updateShortAnswerForm(shortIndex, 'analysis', data.analysis || '')
        updateShortAnswerForm(shortIndex, 'difficulty', data.difficulty)
        updateShortAnswerForm(shortIndex, 'classId', data.classId)
        break
      case 'blank':
        activeTab.value = 'blank'
        const blankIndex = addBlankForm()
        await nextTick() // 等待表单数据初始化
        // 将逗号分隔的答案字符串转换为数组
        const blanks = data.answer ? data.answer.split(',').filter((item) => item) : ['']
        updateBlankForm(blankIndex, 'id', data.id)
        updateBlankForm(blankIndex, 'title', data.content)
        updateBlankForm(blankIndex, 'blanks', blanks)
        updateBlankForm(blankIndex, 'analysis', data.analysis || '')
        updateBlankForm(blankIndex, 'difficulty', data.difficulty)
        updateBlankForm(blankIndex, 'classId', data.classId)
        break
    }
  } catch (error) {
    console.error('获取题目详情失败:', error)
    ElMessage.error('获取题目详情失败')
  } finally {
    loading.value = false
  }
}

// 在组件挂载时初始化数据
onMounted(async () => {
  if (questionId.value) {
    await initEditData()
  }
})

// 计算是否显示新增按钮
const shouldShowAddButton = computed(() => {
  switch (activeTab.value) {
    case 'single':
      return singleChoiceForms.value.length === 0
    case 'multiple':
      return multipleChoiceForms.value.length === 0
    case 'judge':
      return judgeForms.value.length === 0
    case 'short':
      return shortAnswerForms.value.length === 0
    case 'blank':
      return blankForms.value.length === 0
    default:
      return true
  }
})

// 添加新题目
const addQuestion = () => {
  const newIndex = addSingleChoiceForm()
  singleChoiceRefs.value[newIndex] = null
}

// 添加多选题
const addMultipleQuestion = () => {
  const newIndex = addMultipleChoiceForm()
  multipleChoiceRefs.value[newIndex] = null
}

// 添加判断题
const addJudgeQuestion = () => {
  const newIndex = addJudgeForm()
  judgeChoiceRefs.value[newIndex] = null
}

// 添加简答题
const addShortQuestion = () => {
  const newIndex = addShortAnswerForm()
  shortAnswerRefs.value[newIndex] = null
}

// 添加填空题
const addBlankQuestion = () => {
  const newIndex = addBlankForm()
  blankRefs.value[newIndex] = null
}

// 删除题目
const removeQuestion = (index: number) => {
  removeSingleChoiceForm(index)
  singleChoiceRefs.value.splice(index, 1)
}

// 删除多选题
const removeMultipleQuestion = (index: number) => {
  removeMultipleChoiceForm(index)
  multipleChoiceRefs.value.splice(index, 1)
}

// 删除判断题
const removeJudgeQuestion = (index: number) => {
  removeJudgeForm(index)
  judgeChoiceRefs.value.splice(index, 1)
}

// 删除简答题
const removeShortQuestion = (index: number) => {
  removeShortAnswerForm(index)
  shortAnswerRefs.value.splice(index, 1)
}

// 删除填空题
const removeBlankQuestion = (index: number) => {
  removeBlankForm(index)
  blankRefs.value.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  // 校验所有类型的题目
  const allValidations = {
    single: singleChoiceRefs.value,
    multiple: multipleChoiceRefs.value,
    judge: judgeChoiceRefs.value,
    short: shortAnswerRefs.value,
    blank: blankRefs.value
  }

  const allErrors: Record<string, string[]> = {} // 使用对象存储每个 tab 的错误
  const allQuestions: any[] = []
  let firstError: string | null = null // 存储第一个错误信息
  let firstErrorIndex: number | null = null // 存储第一个错误的题目索引
  let firstErrorType: string | null = null // 存储第一个错误的题目类型

  console.log('开始校验所有题目...')

  // 遍历所有题型进行校验
  for (const [type, refs] of Object.entries(allValidations)) {
    if (refs.length === 0) continue

    console.log(`正在校验 ${type} 类型的题目...`)
    // 验证当前类型的所有题目
    const validateResults = await Promise.all(
      refs.map((ref, index) => {
        if (!ref) return { valid: true }
        const result = ref.validate()
        console.log(`${type} 题目 ${index + 1} 校验结果:`, result)
        return { ...result, index }
      })
    )

    // 收集当前 tab 的错误
    const errorsWithIndex = validateResults
      .filter((result) => !result?.valid)
      .map((result) => ({ errors: result.errors || [], index: result.index }))

    if (errorsWithIndex.length > 0) {
      console.log(`${type} 类型题目的错误:`, errorsWithIndex)
      allErrors[type] = errorsWithIndex[0].errors
      // 如果还没有第一个错误，设置当前错误为第一个错误
      if (!firstError) {
        firstError = errorsWithIndex[0].errors[0]
        firstErrorIndex = errorsWithIndex[0].index
        firstErrorType = type
        console.log('设置第一个错误:', firstError, '索引:', firstErrorIndex)
        // 自动切换到有错误的标签页
        activeTab.value = type
      }
    }

    // 收集题目数据
    const questions = refs
      .map((ref) => ref?.getFormData())
      .filter(Boolean)
      .map((data) => ({
        ...data,
        type
      }))
    allQuestions.push(...questions)
  }

  // 如果有错误，显示第一个未修复的错误
  if (firstError) {
    console.log('显示错误信息:', firstError)
    ElMessage.error({
      message: firstError,
      duration: 5000 // 显示5秒
    })

    // 等待 DOM 更新后滚动到对应位置
    await nextTick()
    const errorElement = document.querySelector(
      `.question-item:nth-child(${(firstErrorIndex || 0) + 1})`
    )
    if (errorElement) {
      errorElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
    return
  }

  // 如果没有任何题目，显示提示
  if (allQuestions.length === 0) {
    ElMessage.warning({
      message: '请至少添加一道题目',
      duration: 5000
    })
    return
  }

  // 使用 store 中的 submitQuestions 方法获取格式化后的数据
  const submitData = questionStore.submitQuestions()
  // 调用创建题目API
  await QuestionApi.createQuestionList(submitData)

  questionStore.resetAllData()
  // 提示成功
  ElMessage.success('题目创建成功')
  // 显示成功提示
  // 关闭当前标签页并返回列表页
  closeCurrent(route)
  await router.push('/material/question')
}

// 取消
const cancel = () => {
  router.back()
}

// 处理新增题目
const handleAddQuestion = () => {
  switch (activeTab.value) {
    case 'single':
      addQuestion()
      break
    case 'multiple':
      addMultipleQuestion()
      break
    case 'judge':
      addJudgeQuestion()
      break
    case 'short':
      addShortQuestion()
      break
    case 'blank':
      addBlankQuestion()
      break
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 0;
}

.question-card {
  margin: 0;

  :deep(.el-card__body) {
    padding: 8px; // 减小card内部填充
  }
}

.question-tabs {
  margin: 0;

  :deep(.el-tabs__content) {
    overflow: visible;
    padding: 8px;
  }

  :deep(.el-tabs--border-card) {
    border: none;
    box-shadow: none;
  }

  // 减小标签头部的内边距
  :deep(.el-tabs__header) {
    padding: 0;
    margin: 0;
  }

  // 调整标签页内容区域的边距
  :deep(.el-tab-pane) {
    padding: 8px 0;
  }
}

.question-list {
  padding: 0px;
}

.question-item {
  margin-bottom: 24px;
  padding: 24px;
  background-color: var(--el-fill-color-blank);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  }

  // 移除最后一个题目的下边距
  &:last-child {
    margin-bottom: 0;
  }

  // 移除分隔线，因为现在每个题目都有了明显的边界
  :deep(.el-divider) {
    display: none;
  }
}

.form-actions {
  position: relative;
  height: 70px; // 为固定按钮留出空间
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background-color: var(--el-bg-color);
  padding: 12px 0;
  display: flex;
  justify-content: center;
  gap: 12px;
  box-shadow: 0 -2px 12px 0 rgba(0, 0, 0, 0.1);

  // 确保按钮在内容区域内居中
  width: 100%;
  max-width: calc(100% - 200px); // 减去左侧菜单的宽度
  margin-left: 200px; // 左侧菜单的宽度
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  background-color: var(--el-fill-color-blank);
  border-radius: 4px;
  margin: 20px;
}

// 移除不需要的样式
.box-card,
.card-header,
.title {
  display: none;
}
</style>
